package com.llap.exp190929.service;

import com.llap.exp190929.entity.Blog;
import com.llap.exp190929.entity.User;
import com.llap.exp190929.repository.BlogRepository;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class BlogService {
    private BlogRepository blogRepository;

    public Blog findBlog(int id) {
        return blogRepository.findById(id).orElse(null);
    }

    public Page<Blog> findBlogs(int page, int pageSize) {
        return findBlogs(page, pageSize, null);
    }

    public Page<Blog> findBlogs(int page, int pageSize, User user) {
        Pageable paginator = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));
        if (user != null) return blogRepository.findAllByUser(user, paginator);
        return blogRepository.findAll(paginator);
    }

    @Transactional
    public Blog addBlog(Blog blog) {
        if (blog.getId() != null) return null;
        return blogRepository.save(blog);
    }

    @Transactional
    public Blog updateBlog(Blog blog) {
        if (blog.getId() == null) return null;
        return blogRepository.save(blog);
    }

    @Transactional
    public void deleteBlog(int id) {
        blogRepository.deleteById(id);
    }
}
